var top_bar_h = 70, page_h = 60;

var layform, layer, layedit, laydate, tableSelect,layUpload;

var conlums, approveConlums, searchColumns = {};

var baseAttachmentJson = [];

var table_list;

var url;
var icode = "530000";

var loding = null;
var lodingCheck = null;
var dblclickListApi = null;

var option = ['确认', '取消'];
var ary = new Array();
ary.push('确认');

function get_content_h() {
    var search_h = 0, tool_bar_h = 0;
    if ($('.search').length > 0)
        search_h = $('.search').get(0).offsetHeight+10;
    if ($('.search-top').length > 0)
       tool_bar_h = $('.search-top').get(0).offsetHeight+10;

    var height = (document.documentElement.offsetHeight || document.body.offsetHeight) -
        page_h - search_h - tool_bar_h-16;
    return height;
}

function get_form_h() {
    return (document.documentElement.offsetHeight || document.body.offsetHeight) - 110;
}

$(function() {
    table_list = $('#table_list');

    init_handle();

});

/**
 * 登录信息获取
 */
function getUserInfo(fn) {
    var data = This.jqueryAjax(Api.base.user.userInfo, {});
    if(data.status == 1) {
        // 取出数据
        fn.call("", data.object);
    } else {
        layerMessageOk(data.message);
    }
}

function init_table(url, conlums,pageSize,method,queryParams,singleSelect, height,params) {
    var obj = {
        url: url,
        method: method || "get",
        height: height || get_content_h(),
        paginationLoop: false,
        columns: conlums,
        pagination: true,
        pageNumber: 1,
        singleSelect: singleSelect == false ? false : true,
        pageSize: pageSize || 20,
        buttonsClass: "btn-primary btn-sm",
        clickToSelect : true, // 点击选中
        sidePagination:'server',
        queryParams:function(param){
            if(queryParams){
                $.extend(param,typeof queryParams =="object"?queryParams:queryParams());
            }
            $("#searchForm input").each(function() {
                if ($.trim($(this).val())) searchColumns[$(this).attr("name")] = $.trim($(this).val());
            });
            $("#searchForm select").each(function() {
                if ($.trim($(this).val())) searchColumns[$(this).attr("name")] = $.trim($(this).val());
            });
            $.extend(param, searchColumns);
            param['t'] = new Date().getTime();
            return param;
        },
        onDblClickRow: function(row, $element) {
            onDblClickRowInit(row, $element);
        },
        onLoadSuccess: function() {
            try {
                tableLoadSuccess("table_list");
            } catch (e) {
            }
            _loadingClose();
        }
    };
    if(params){
        $.extend(obj,params);
    }
    table_list.bootstrapTable(obj);
}

function init_table_no_page(table, url, conlums, dataField, pageSize, method, queryParams, singleSelect, height) {
    var table_list_no_page = table ? $('#' + table) : table_list;
    table_list_no_page.bootstrapTable({
        url: url,
        method: method || "get",
        height: height || get_content_h(),
        paginationLoop: false,
        columns: conlums,
        dataField: dataField,
        pagination: false,
        pageNumber: 1,
        singleSelect: singleSelect == false ? false : true,
        pageSize: pageSize || 20,
        buttonsClass: "btn-primary btn-sm",
        clickToSelect : true, // 点击选中
        sidePagination:'server',
        queryParams:function(param){
            if(queryParams){
                $.extend(param,typeof queryParams =="object"?queryParams:queryParams());
            }
            /*var searchColumns={};
            $("#searchForm input").each(function() {
                if ($.trim($(this).val())) searchColumns[$(this).attr("name")] = $.trim($(this).val());
            });
            $("#searchForm select").each(function() {
                if ($.trim($(this).val())) searchColumns[$(this).attr("name")] = $.trim($(this).val());
            });*/
            $.extend(param, searchColumns);
            param['t'] = new Date().getTime();
            return param;
        },
        onDblClickRow: function(row, $element) {
            onDblClickRowInit(row, $element);
        },
        onLoadSuccess: function() {
            _loadingClose();
        }
        // onClickRow: function (row) {
        //     onClickRowInit(row, $element);
        //  },
    });
}

// 直接添加数据初始化table
function init_table_data(object, data, conlums, height, pageSize, singleSelect, pagination, clickToSelect) {
    $("#" + object).bootstrapTable({
        data: data,
        height: height || get_content_h(),
        paginationLoop: false,
        columns: conlums,
        pagination: pagination == false? false : true,  // 是否显示分页
        pageNumber: 1,
        singleSelect: singleSelect == false? false : true,
        pageSize: pageSize || 20,
        buttonsClass: "btn-primary btn-sm",
        clickToSelect : clickToSelect == false? false : true, // 点击选中
        onDblClickRow: function(row, $element) {
            onDblClickRowInit(row, $element);
        },
        onPostBody: function() {
        },
        onLoadSuccess: function() {
            try {
                tableLoadSuccess();
            } catch (e) {

            }
            _loadingClose();
        }
    });
}

function onDblClickRowInit(row, $element){
    if (dblclickListApi) {
        var url = dblclickListApi.URL;
        var title = dblclickListApi.TITLE;
        var width = dblclickListApi.WIDTH || "80%";
        var height = dblclickListApi.HEIGHT || "80%";
        if("#" == url){return;}
        var id = dblclickListApi.ID;
        var params = dblclickListApi.PARAMS;
        var paramsAdd = dblclickListApi.PARAMSADD;
        var paramStr = null;
        var str = "view=1&id=" + row[id];
        if (params) {
            if(params == "row"){
                str += '&row=' + encodeURIComponent(encodeURIComponent(JSON.stringify(row)));
            } else {
                for (var i = 0; i < params.length; i++) {
                    if(params[i] == 'ProcessType'){
                        str += '&Type=' + row[params[i]];
                    }else{
                        str += '&' + params[i] + '=' + row[params[i]];
                    }
                }
            }
        }

        if (paramsAdd) {
            var paramArr = [];
            for (var key in paramsAdd) {
                var param = [key, paramsAdd[key]].join("=");
                paramArr.push(param);
            }
            paramStr = paramArr.join("&");
        }

        if (url) {
            if (url.indexOf("?") >= 0) {
                top.popup(url + "&" + str + "&" + paramStr, title, width, height);
            } else {
                top.popup(url + "?" + str + "&" + paramStr, title, width, height);
            }
        }
    }
    try {
        privateOnDblClickRowInit(row, $element);
    } catch (e) {

    }
}

function init_table_list_approval(object, url, conlums, height, pageSize, method, queryParams, pagination) {
    $("#" + object).bootstrapTable({
        url: url,
        method: method || "get",
        height: height || get_content_h(),
        paginationLoop: false,
        columns: conlums,
        pagination: pagination == false ? false : true,  // 是否显示分页
        singleSelect: true,
        pageNumber: 1,
        pageSize: pageSize || 20,
        buttonsClass: "btn-primary btn-sm",
        clickToSelect: true, // 点击选中
        sidePagination: 'server',
        queryParams: function (param) {
            if (queryParams) {
                $.extend(param, queryParams());
            } else {
                var searchColumns = {};
                $("#searchForm input").each(function () {
                    if ($.trim($(this).val())) searchColumns[$(this).attr("name")] = $.trim($(this).val());
                });
                $("#searchForm select").each(function () {
                    if ($.trim($(this).val())) searchColumns[$(this).attr("name")] = $.trim($(this).val());
                });
                $.extend(param, searchColumns);
            }
            param['t'] = new Date().getTime();
            return param;
        },
        onLoadSuccess: function () {
            try {
                tableLoadSuccess(object);
            } catch (e) {
            }
            _loadingClose();
        }
    });
}

function init_table_list(object, url, conlums, height, pageSize, method, queryParams, pagination) {
    $("#" + object).bootstrapTable({
        url: url,
        method: method || "get",
        height: height || get_content_h(),
        paginationLoop: false,
        columns: conlums,
        pagination: pagination == false ? false : true,  // 是否显示分页
        singleSelect: true,
        pageNumber: 1,
        pageSize: pageSize || 20,
        buttonsClass: "btn-primary btn-sm",
        clickToSelect : true, // 点击选中
        sidePagination:'server',
        queryParams:function(param){
            if(queryParams){
                $.extend(param,queryParams());
            }else {
                /*var searchColumns={};
                $("#searchForm input").each(function() {
                    if ($.trim($(this).val())) searchColumns[$(this).attr("name")] = $.trim($(this).val());
                });
                $("#searchForm select").each(function() {
                    if ($.trim($(this).val())) searchColumns[$(this).attr("name")] = $.trim($(this).val());
                });
                $.extend(param,searchColumns);*/
            }
            $.extend(param, searchColumns);
            param['t'] = new Date().getTime();
            return param;
        },
        onDblClickRow: function(row, $element) {
            onDblClickRowInit(row, $element);
        },
        onLoadSuccess: function() {
            try {
                tableLoadSuccess(object);
            } catch (e) {
            }
            _loadingClose();
        }
    });
}

function init_table_search(params, tab_list) {
    if (tab_list) {
        $("#" + tab_list).bootstrapTable('refresh');
    } else {
        table_list.bootstrapTable('refresh');
    }
}

function closeFlushParent (parent) {
    var index = parent.layer.getFrameIndex(window.name);
    try {
        var doc = top.document.getElementById("iframe" + top.MODULE_ID).contentWindow;
        doc.windowloadList();
    } catch (e) {
    }
    parent.layer.close(index);
}

function getTopParent () {
    try {
        var doc = top.document.getElementById("iframe" + top.MODULE_ID).contentWindow;
        return doc;
    } catch (e) {
    }
}
function init_handle() {
    pressEnter("#searchForm", "$('.searchListener').click()");
    pressEnter("#searchFormH", "$('.searchListenerH').click()");

    $(".searchListener").click(function(){

        searchColumns = {};
        var tab_id = $(this).attr("tab_id");
        var tat_list = $(this).attr("table_list");
        if (tab_id) {

            $("#" + tab_id + " #searchForm input").each(function() {
                if ($(this).val()) searchColumns[$(this).attr("name")] = $(this).val().trim();
            });
            $("#" + tab_id + " #searchForm select").each(function() {
                if ($(this).val()) searchColumns[$(this).attr("name")] = $(this).val().trim();
            });
        } else {
            $("#searchForm input").each(function() {
                if ($(this).val()) searchColumns[$(this).attr("name")] = $(this).val().trim();
            });
            $("#searchForm select").each(function() {
                if ($(this).val()) searchColumns[$(this).attr("name")] = $(this).val().trim();
            });
        }

        init_table_search(searchColumns, tat_list);

    });

    $(".searchListenerH").click(function () {

        searchColumns = {};
        var tab_id = $(this).attr("tab_id");
        var tab_list = $(this).attr("table_list");

        if (tab_id) {
            $("#" + tab_id + " #searchFormH input").each(function () {
                if ($(this).val()) searchColumns[$(this).attr("name")] = $(this).val().trim();
            });
            $("#" + tab_id + " #searchFormH select").each(function () {
                if ($(this).val()) searchColumns[$(this).attr("name")] = $(this).val().trim();
            });
        } else {
            $("#searchFormH input").each(function () {
                if ($(this).val()) searchColumns[$(this).attr("name")] = $(this).val().trim();
            });
            $("#searchFormH select").each(function () {
                if ($(this).val()) searchColumns[$(this).attr("name")] = $(this).val().trim();
            });
        }
        init_table_search(searchColumns, tab_list);

    });

    //高级搜索清空
    $(".clearall").click(function () {
        var tab_id = $(this).attr("tab_id");
        var tab_list = $(this).attr("table_list");
        if (tab_id) {
            $("#" + tab_id + " #searchForm input").val("");
            $("#" + tab_id + " #searchForm select").val("");
            $("#" + tab_id + " #searchFormH input").val("");
            $("#" + tab_id + " #searchFormH select").val("");
        } else {
            $("#searchForm input").val("");
            $("#searchForm select").val("");
            $("#searchFormH input").val("");
            $("#searchFormH select").val("");
        }

        searchColumns = [];
        init_table_search(searchColumns, tab_list);

    });

    $(".up_layer").click(function() {
        layer.alert("我是从上面来的消息！", {
            shade: 0.2,
            anim: 1,
            time: 2000 //2秒后自动关闭
        })
    });
    $(".footer_layer").click(function() {
        layer.open({
            type: 2,
            title: "我是从右下角来的消息！",
            closeBtn: 0, //不显示关闭按钮
            shade: 0.2,
            area: ['340px', '215px'],
            offset: 'rb', //右下角弹出
            time: 2000, //2秒后自动关闭
            anim: 2,
            content: "message.html"
        });
    });

}

function layuiReady (fn, isLoading) {
    layui.use(['form', 'layer', 'layedit', 'laydate','upload'], function() {
        layform = layui.form,
        layer = layui.layer,
        layedit = layui.layedit,
        laydate = layui.laydate;
        layUpload = layui.upload;

        if (isLoading != '0') {
            //加载等待
            _loading();
        }

        setTimeout(function () {
            return fn.call();
        }, 100);

        setTimeout(function () {
            _loadingClose();
        }, 2000);
    });
}

function dateFormat (jsonDate, format) {
    if(!jsonDate){
        return "";
    }

    //json日期格式转换为正常格式
    // 判断时间类型 为 String 还是 datatime
    if (typeof(jsonDate) == 'string' ) {
        if(jsonDate.indexOf("T") != -1){
            jsonDate = jsonDate.replace("T", " ");
        }
        jsonDate = new Date(jsonDate.replace(/-/g,"/")).getTime();
    }

    var jsonDateStr = jsonDate.toString();//此处用到toString（）是为了让传入的值为字符串类型，目的是为了避免传入的数据类型不支持.replace（）方法
    try {
        var k = parseInt(jsonDateStr.replace("/Date(", "").replace(")/", ""), 10);
        // if (k < 0)
        //     return null;

        var date = new Date(parseInt(jsonDateStr.replace("/Date(", "").replace(")/", ""), 10));
        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();

        if (format == "yyyy-MM-dd") {
            return date.getFullYear() + "-" + month + "-" + day;
        }
        if (format == "yyyy年MM月dd日") {
            return date.getFullYear() + "年" + month + "月" + day + "日";
        }
        if(format == "yyyy"){
            return date.getFullYear();
        }
        if(format == "MM"){
            return month;
        }
        if(format == "dd"){
            return day;
        }

        var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
        var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        var milliseconds = date.getMilliseconds();
        if (format == "yyyy-MM-dd hh:mm") {
            return date.getFullYear() + "-" + month + "-" + day + " " + hours + ":" + minutes;
        }
        if (format == "yyyy-MM") {
            return date.getFullYear() + "-" + month;
        }
        if (format == "yyyy-MM-dd hh:mm:ss" || format == "yyyy-MM-dd HH:mm:ss") {
            return date.getFullYear() + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
        }

        //return date.getFullYear() + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
        return date.getFullYear() + "-" + month + "-" + day;
    } catch (ex) {
        return "时间格式转换错误";
    }
}

// 弹出窗口
function popup (url, title, width, height, parameter) {
    if(width == "" || width == null){
        width = "80%";
    }
    if(height == "" || height == null){
        height = "80%";
    }
    var object = {
        type: 2,
        title: title,
        shadeClose: false,
        shade: 0.2,
        area: [width, height],
        content: url, //iframe的url
        url: url //url
    };
    if (parameter) {
        $.extend(object, parameter);
    }
    layer.open(object);

    var w = 0, h = 0;
    if (width.indexOf("%") != -1) {
        w = ((100 - Number(width.replace("%", ""))) / 2 / 100) * top.document.documentElement.clientWidth;
        h = ((100 - Number(height.replace("%", ""))) / 2 / 100) * top.document.documentElement.clientHeight;
        top.IFRAME_W_H = [];
        top.IFRAME_W_H.push(w);
        top.IFRAME_W_H.push(h);
    }

    //top.IFRAME_TOP.push(layer.index);
}

function locationUrl (url, title, width, height,parameter) {
    if (url) {
        if (width == "" || width == null){
            width = "80%";
        }
        if(height == "" || height == null){
            height = "80%";
        }
        if (url.indexOf("?") != -1) {
            url = url + "&t=" + new Date().getTime();
        } else {
            url = url + "?t=" + new Date().getTime();
        }
        if (url.indexOf("windowName=") == -1) {
            var windowName = window.name;
            url += "&windowName=" + windowName;
        }
        top.popup(url + "&t=" + new Date().getTime(), title, width, height,parameter);
    }
}

function bindIfrCallCtx(ctx) {
    if (ctx) {
        return {
            success: function (layero, index) {
                var ifrWin = $(layero).find('iframe')[0].contentWindow;
                ctx = $.extend({}, ctx, {layero: layero, layerIndex: index});
                var fn = ctx.callback;
                if ($.isFunction(fn)) {
                    ctx.callback = function () {
                        var args = Array.prototype.slice.call(arguments);
                        // 放第一位还是最后一位好?
                        args.push(ctx);
                        // args = [ctx].concat(args);
                        fn.apply(ctx, args);
                    };
                }
                ifrWin.ifrCallCtx = ctx;
            }
        }
    }
}

function tryApplyIfrCallback() {
    var args = $.makeArray(arguments);
    var ifrCallCtx = window.ifrCallCtx || {};
    var fn = ifrCallCtx.callback;
    if ($.isFunction(fn)) {
        var retVal = fn.apply(null, args);
        if(retVal !== false) {
            toClose();
        }
    } else {
        toClose();
    }
}

//修改弹出窗口
function commonAdd(url, title, width, height) {

    if (width == "" || width == null) {
        width = "80%";
    }
    if (height == "" || height == null) {
        height = "80%";
    }
    if (url) {
        if (url.indexOf("?") != -1) {
            url = url + "&t=" + new Date().getTime();
        } else {
            url = url + "?t=" + new Date().getTime();
        }
        if (url.indexOf("windowName=") == -1) {
            var windowName = window.name;
            url += "&windowName=" + windowName;
        }
        top.popup(url + "?t=" + new Date().getTime(), title, width, height);
    }
}

//修改弹出窗口
function commonUpdate(url, id, title, stateName, width, height) {
    if(width == "" || width == null){
        width = "80%";
    }
    if(height == "" || height == null){
        height = "80%";
    }
    if (url) {
        // 获取选中的行数据数组
        var row = select_one_row();
        if (row) {
            id = row[id];
        } else {
            return;
        }
        if (url.indexOf("?") != -1) {
            url = url + "&t=" + new Date().getTime();
        } else {
            url = url + "?t=" + new Date().getTime();
        }
        if (url.indexOf("windowName=") == -1) {
            var windowName = window.name;
            url += "&windowName=" + windowName;
        }
        top.popup(url + "?id=" + id + "&t=" + new Date().getTime(), title, width, height);
    }
}
//查看并弹出窗口
function generalView(url, id, title, stateName, width, height){
    if(width == "" || width == null){
        width = "80%";
    }
    if(height == "" || height == null){
        height = "80%";
    }
    if (url) {
        if (url.indexOf("?") != -1) {
            top.popup(url + "&view=1&id=" + id + "&t=" + new Date().getTime(), title, width, height);
        } else {
            top.popup(url + "?view=1&id=" + id + "&t=" + new Date().getTime(), title, width, height);
        }
    }
}
//修改弹出窗口
function generalUpdate(url, id, title, stateName, width, height) {
	event || (event = window.event);
	event.stopPropagation ? event.stopPropagation() : (event.cancelBubble = true);
	if(width == "" || width == null){
      width = "80%";
  }
  if(height == "" || height == null){
      height = "80%";
  }
  if (url) {
      if (url.indexOf("?") != -1) {
          url = url + "&t=" + new Date().getTime();
      } else {
          url = url + "?t=" + new Date().getTime();
      }
      if (url.indexOf("windowName=") == -1) {
          var windowName = window.name;
          url += "&windowName=" + windowName;
      }
      top.popup(url + "?id=" + id + "&t=" + new Date().getTime(), title, width, height);
  }
}

//不弹窗修改
function generalNopopupUpdate(url, id, title, stateName, width, height) {
    if(width == "" || width == null){
        width = "80%";
    }
    if(height == "" || height == null){
        height = "80%";
    }
    if (url) {
        if (url.indexOf("?") != -1) {
            url = url + "&t=" + new Date().getTime();
        } else {
            url = url + "?t=" + new Date().getTime();
        }
        if (url.indexOf("windowName=") == -1) {
            var windowName = window.name;
            url += "&windowName=" + windowName;
        }
        var parameter=url + "?id=" + id + "&t=" + new Date().getTime()
        var object = {
            type: 2,
            title: title,
            shadeClose: false,
            shade: 0.2,
            area: [width, height],
            content: url, //iframe的url
            url: url //url
        };
        if (parameter) {
            $.extend(object, parameter);
        }
        layer.open(object);
    }
}

//详情
function commonView(url, id, title, width, height) {
    if(width == "" || width == null){
        width = "80%";
    }
    if(height == "" || height == null){
        height = "80%";
    }
    if (url) {
        // 获取选中的行数据数组
        var row = select_one_row();
        if (row) {
            id = id ? row[id] : row["id"];
        } else {
            return;
        }
        if (url.indexOf("?") != -1) {
            top.popup(url + "&view=1&id=" + id + "&t=" + new Date().getTime(), title, width, height);
        } else {
            top.popup(url + "?view=1&id=" + id + "&t=" + new Date().getTime(), title, width, height);
        }
    }
}

//详情
function commonViewTab(tab, url, id, title, width, height) {
    if(width == "" || width == null){
        width = "80%";
    }
    if(height == "" || height == null){
        height = "80%";
    }
    if (url) {
        // 获取选中的行数据数组
        var row = select_one_row(tab);
        if (row) {
            id = id ? row[id] : row["id"];
        } else {
            return;
        }
        if (url.indexOf("?") != -1) {
            top.popup(url + "&view=1&id=" + id + "&t=" + new Date().getTime(), title, width, height);
        } else {
            top.popup(url + "?view=1&id=" + id + "&t=" + new Date().getTime(), title, width, height);
        }
    }
}

// 删除
function commonDelete(url, id, stateName, callBack) {
    var ids = "";
    id = id || "id";
    if (id) {
        ids = select_more_row(id);
    }
    if (!ids) {
        //layerMessage("没有选中任何条目!", 7);
        return;
    }

    Layui.confirm("删除后不可恢复，确定要删除吗？", '', function(layer, index) {
        var data = This.jqueryAjax(url, {ids: ids});
        if (data.status == 1) {
            layerMessage(data.message || '删除成功！');
            closeFlushParent(parent);
            // 成功后，若有回调则执行回调
            if(callBack){
                callBack();
            }
        } else if (data.status == -1) {
            layerMessage(data.message || '删除失败！', 2);
            toClose();
        }
    });
}

//删除
function generalDelete(url, id, stateName, callBack) {
	event || (event = window.event);
	event.stopPropagation ? event.stopPropagation() : (event.cancelBubble = true);
	var ids = "";
	//id = id || "id";
	//if (!ids) {
	    //layerMessage("没有选中任何条目!", 7);
	    //return;
	//}
	
	Layui.confirm("确定要删除吗？", '', function(layer, index) {
	    var data = This.jqueryAjax(url, {id: id});
	    if (data.status == 1) {
	        layerMessage(data.message || '删除成功！');
	        closeFlushParent(parent);
	        // 成功后，若有回调则执行回调
	        if(callBack){
	            callBack();
	        }
	    } else if (data.status == -1) {
	        layerMessage(data.message || '删除失败！', 2);
	        toClose();
	    }
	});
}

function select_one_row (table, message) {
    var _table = table_list;
    if (table) {
        _table = $("#" + table);
    }
    message = message || "请选择一条记录！";
    var selects = _table.bootstrapTable('getSelections');
    if (selects && selects.length > 0 && !isElement(selects[0])) {
        if (selects.length == 1) {
            return selects[0];
        } else {
            // 消息弹框
            layerMessage("最多只能选择一条记录！", 2);
            return false;
        }
    } else {
        // 消息弹框
        layerMessage(message, 7);
        return false;
    }
}

function select_more_row(id, table, message){
    var ids = '';
    var _table = table_list;
    if (table) {
        _table = $("#" + table);
    }
    var selects = _table.bootstrapTable('getSelections');
        if (selects && selects.length > 0) {
        if(id){
            for (var i = 0; i < selects.length; i++) {
                if (id) {
                    ids += selects[i][id] + ",";
                } else {
                    ids += selects[i].id + ",";
                }
            }
            if (ids) ids = ids.substring(0, ids.length - 1);
            return ids;
        } else {
            if (selects[0].id && (selects[0].id == id || selects[0].id == 'table_list')){
                // 消息弹框
                layerMessage(message || "最少选择一条记录！", 7);
                return false;
            } else {
                return selects;
            }
        }
    } else {
        // 消息弹框
        layerMessage(message || "最少选择一条记录！", 7);
        return false;
    }
}


function layerMessageOk (message, fn) {
    Layui.confirm(message, {
        btn: ['确定']
    }, function(layer, index) {
        if (fn) {
            return fn.call(1);
        }
    });
}

/**
 * 消息弹框
 * @param message
 * @param icon 可选 图标1-7
 * @return
 */
function layerMessage(data, icon, time) {
    var message = data || "数据提交出错！";
    if (data && data.message) {
        message = data.message;
    }
    top.layer.msg(message, {
        icon: icon || 1,
        time: time ? time * 1000 : 2000
    });
}

//子集ifram调用父级的接收方法
function parent_receive (message,icon) {
    icon=icon?icon:1;
    if (message) {
        layer.msg(message, {
            icon: icon,
            time: 1000
        });
    }
}

function windowloadList(tb) {

    $("#searchForm input").val("");
    $("#searchForm select").val("");
    $("#searchFormH input").val("");
    $("#searchFormH select").val("");

    init_table_search(searchColumns, tb);
}

function uploadCallback(json) {

}

String.prototype.endWith = function(endStr){
    var d = this.length - endStr.length;
    return (d >= 0 && this.lastIndexOf(endStr) == d)
}

function receiveSuccessUpload (json) {
    var html =
    '<li name="' + json.fileName + '">\n' +
        '<img width="16px" height="16px" src="/admin/images/file_extension_doc.png">' + json.fileName + '&nbsp;&nbsp;\n' +
        '<a href="javascript:void(0);" title="删除" onclick="uploadDel(this, \'' + json.fileName + '\', \'' + json.category + '\');">\n' +
            '<img src="/admin/images/DeleteRed.png" alt="删除" width="16px" height="16px">\n' +
        '</a>\n' +
        '<input type="hidden" value="' + json.fileName + '">&nbsp;&nbsp;|&nbsp;&nbsp;\n' +
        '<a data-folder="pro" filepath="' + json.filePath + '" href="javascript:;" title="预览" onclick="previewFile(this)">\n' +
            '<img src="/admin/images/reading_view.png" width="16px" height="16px" alt="预览">\n' +
        '</a>\n' +
    '</li>';

    var category = replaceComponent(json.category);

    $(".receiveFileList" + category).after(html);

    baseAttachmentJson.push(json);

    receivepPrivateSuccessUpload(json,category);

}

function receivepPrivateSuccessUpload(json, category) {

}

function previewFile (_this) {
    var filepath = $(_this).attr("filepath");
    //filepath = filepath.replace(".docx", ".pdf").replace(".doc", ".pdf");
    if (!filepath.endWith(".pdf") && !filepath.endWith(".doc") && !filepath.endWith(".docx")) {
        top.popup("/admin/pdf/web/jpg.html?file=" + filepath, "图片预览", "80%", "90%", '', 1000);
    } else {
        top._loading();
        setTimeout(function () {
            This.jqueryAjax(Api.common.downPdf, {urlStr: filepath}, 'json',function(data) {
                top._loadingClose();
                if (data && data.status == 1) {
                    top.popup("/admin/pdf/web/viewer.html?file=" + data.object, "文件预览", "80%", "90%", '', 1000);
                }
            });
        }, 100);
    }
}

function uploadDel (_this, fileName, category) {
    for (var i = 0; i < baseAttachmentJson.length; i++) {
        if (baseAttachmentJson[i].fileName == fileName && baseAttachmentJson[i].category == category) {
            baseAttachmentJson[i]["deleteMark"] = 1;
        }
    }
    if (_this) {
        $(_this).parent().remove();
    }
    removeFileArray(category, fileName);
}

function removeFileArray(category, fileName){

}

function initUploadFile (array,filterStrBefore,filterStrAfter,isSingle) {

    if(!filterStrBefore){
        filterStrBefore="";
    }
    if(!filterStrAfter){
        filterStrAfter="";
    }
    for (var i = 0; i < array.length; i++) {
        var json = array[i];
        if (json.category != 'PerPhoto') {
            var html =
                '<li name="' + json.fileName + '">\n' +
                '<img width="16px" height="16px" src="/admin/images/file_extension_doc.png">' + json.fileName + '&nbsp;&nbsp;\n' +
                '<a href="javascript:void(0);" title="删除" onclick="uploadDel(this, \'' + json.fileName + '\', \'' + filterStrBefore +json.category+ filterStrAfter + '\');">\n' +
                '<img src="/admin/images/DeleteRed.png" alt="删除" width="16px" height="16px">\n' +
                '</a>\n' +
                '<input type="hidden" value="' + json.fileName + '">&nbsp;&nbsp;|&nbsp;&nbsp;\n' +
                '<a data-folder="pro" filepath="' + json.filePath + '" href="javascript:;" title="预览" onclick="previewFile(this)">\n' +
                '<img src="/admin/images/reading_view.png" width="16px" height="16px" alt="预览">\n' +
                '</a>\n' +
                '<a data-folder="pro" filepath="' + json.filePath + '" filename="' + json.fileName + '" href="javascript:;" title="下载" onclick="downFile(this)">\n' +
                '<img src="/admin/images/reading_down.png" width="16px" height="16px" alt="下载">\n' +
                '</a>\n' +
                '</li>';

            var category = replaceComponent(json.category);
            $(".receiveFileList" + filterStrBefore + category + filterStrAfter).after(html);
            if(isSingle){
                $(".receiveFileList" + filterStrBefore + category + filterStrAfter).nextAll().filter('i').hide();
            }

            array[i]["dataId"] = "";
            baseAttachmentJson.push(array[i]);
        }
    }
    //查看时删除删除按钮 提前实现方法 window.removeFileDelete
    if(window.removeFileDelete){
        removeFileDelete();
    }
}

//替换特殊字符
function replaceComponent(category) {
    category = category.replace(/\+/g, "");
    category = category.replace(/\ /g, "");
    category = category.replace(/\//g, "");
    category = category.replace(/\#/g, "");
    category = category.replace(/\&/g, "");
    category = category.replace(/\?/g, "");
    category = category.replace(/\(/g, "");
    category = category.replace(/\)/g, "");
    category = category.replace(/\（/g, "");
    category = category.replace(/\）/g, "");
    return category;
}

//获取附件是否存在
function getBaseAttachment (category) {
    if (baseAttachmentJson.length > 0) {
        for (var i = 0; i < baseAttachmentJson.length; i++) {
            if (baseAttachmentJson[i].category == category && baseAttachmentJson[i].deleteMark != 1) {
                return true;
            }
        }
    }
    return false;
}

/**
 * 多字典下拉框字典初始化
 * @param eleid
 * @param firstMassage
 * @param data
 * @constructor
 */
function jsonBindDrop(eleid, firstMassage, data, object){
    var key = eleid.replace("#", "");
    var val = object && object[key];
    // 下拉框
    var str = "";
    if (firstMassage) {
        str = "<option value=''>" + firstMassage + "</option>";
    }
    for (var i = 0; i < data.length; i++) {
        // 一级
        if (val && val == data[i].code) {
            str += "<option value='" + data[i].code + "' selected='selected'>" + data[i].name + "</option>";
        } else {
            str += "<option value='" + data[i].code + "'>" + data[i].name + "</option>";
        }
    }
    $(eleid).html(str);
}

//下拉字典
function initUrlSelectDic(id, url, code, value) {
    This.jqueryAjax(url, {}, "json", function (data) {
        if (data && data.status == 1) {
            var dataObj = data.object;
            bindSelect("#" + id, "==请选择==", dataObj, value, code);
        }
    });
}

//下拉字典
function initUrlSelectDic_2(id, url, code, value) {
  This.jqueryAjax(url, {}, "json", function (data) {
      if (data && data.status == 1) {
          var dataObj = data.object;
          bindSelect_2("#" + id, "==请选择==", dataObj, value, code);
      }
  });
}

//下拉字典
function initUrlSelectDic_3(id, url, code, value) {
	This.jqueryAjax(url, {}, "json", function (data) {
	    if (data && data.status == 1) {
	        var dataObj = data.object;
	        bindSelect_3("#" + id, "==请选择==", dataObj, value, code);
	    }
	});
}

//下拉字典
function initUrlSelectDic_provinceCity(id, url, code, value, param) {
	This.jqueryAjax(url, {parentId: param}, "json", function (data) {
	    if (data && data.status == 1) {
	        var dataObj = data.object;
	        bindSelect("#" + id, "==请选择==", dataObj, value, code);
	    }
	});
}

function initUrlSelectDicByParentCode(id, url, code, value, param) {
	This.jqueryAjax(url, {code: param}, "json", function (data) {
	    if (data && data.status == 1) {
	        var dataObj = data.object;
	        bindSelect("#" + id, "==请选择==", dataObj, value, code);
	    }
	});
}

//下拉字典
function initUrlSelectDicPage(id, url, code, value, nameField) {
    This.jqueryAjax(url, {}, "json", function (data) {
        if (data && data.list.length > 0) {
            var dataObj = data.list;
            bindSelect("#" + id, "==请选择==", dataObj, value, code, nameField);
        }
    });
}

//下拉字典
function initUrlSelectDicPageObject(id, url, code, value, nameField) {
    This.jqueryAjax(url, {}, "json", function (data) {
        if (data && data.object) {
            var dataObj = data.object;
            bindSelect("#" + id, "==请选择==", dataObj, value, code, nameField);
        }
    });
}

//绑定下拉字典
function bindSelect(eleid, firstMassage, data, value, showField, nameField) {
    var name = nameField ? nameField : 'name';
    // 下拉框
    var str = "<option value=''>" + firstMassage + "</option>";
    for (var i = 0; i < data.length; i++) {
        // 一级
        if (showField) {
            if(data[i][showField] == value){
                str += "<option selected='selected' value='" + data[i][showField] + "'>" + data[i][name] + "</option>";
            }else{
                str += "<option value='" + data[i][showField] + "'>" + data[i][name] + "</option>";
            }
        }else{
            if (data[i].code == value){
                str += "<option selected='selected' value='" + data[i].code + "'>" + data[i][name] + "</option>";
            }else{
                str += "<option value='" + data[i].code + "'>" + data[i][name] + "</option>";
            }
        }
    }
    $(eleid).html(str);
    layform.render("select");
}

//绑定下拉字典
function bindSelect_2(eleid, firstMassage, data, value, showField) {
  // 下拉框
  var str = "<option value=''>" + firstMassage + "</option>";
  for (var i = 0; i < data.length; i++) {
      // 一级
      if (showField) {
          if(data[i].years == value){
              str += "<option selected='selected' value='" + data[i][showField] + "'>" + data[i].years + "</option>";
          }else{
              str += "<option value='" + data[i][showField] + "'>" + data[i].years + "</option>";
          }
      }else{
          if (data[i].code == value){
              str += "<option selected='selected' value='" + data[i].code + "'>" + data[i].years + "</option>";
          }else{
              str += "<option value='" + data[i].code + "'>" + data[i].years + "</option>";
          }
      }
  }
  $(eleid).html(str);
  try {
      layform.render("select");
  }catch (e) {

  }

}

//绑定下拉字典
function bindSelect_3(eleid, firstMassage, data, value, showField) {
// 下拉框
var str = "<option value=''>" + firstMassage + "</option>";
for (var i = 0; i < data.length; i++) {
    // 一级
    if (showField) {
        if(data[i][showField] == value){
            str += "<option selected='selected' value='" + data[i][showField] + "'>" + data[i].years + "</option>";
        }else{
            str += "<option value='" + data[i][showField] + "'>" + data[i].years + "</option>";
        }
    }else{
        if (data[i].code == value){
            str += "<option selected='selected' value='" + data[i].code + "'>" + data[i].years + "</option>";
        }else{
            str += "<option value='" + data[i].code + "'>" + data[i].years + "</option>";
        }
    }
}
$(eleid).html(str);
layform.render("select");
}

//绑定下拉字典
function bindSelects(eleid, data, value){
    // 下拉框
    for (var i = 0; i < data.length; i++) {
        // 一级
        if (data[i].code == value) {
            $(eleid).val(data[i].name);
        }
    }
}

function valData (json, elemId) {
    for (var key in json) {
        if(elemId){
            if (!$("#" + elemId).find(("#" + key)).is("select")) {
                $("#" + elemId).find("#" + key).val(json[key]);
            }
        }else {
            if (!$("#" + key).is("select")) {
                $("#" + key).val(json[key]);
            }
        }

    }
}

function initSingleDic (id, code, value) {
    var json = [];
    var item = {"id": id, "code": code};
    json.push(item);
    // 字典查询
    This.jqueryAjax(Api.base.dataDictionary.getDataDictionaryDetailListByCode, {code : JSON.stringify(json)}, "json", function(data){
        for (var key in data.object) {
            var dic_list = data.object[key];
            bindSelect("#" + key, "==请选择==", dic_list, value);
        }
    });
}

function initMoreDic (json, value, noMessage) {
    This.jqueryAjax(Api.base.dataDictionary.getDataDictionaryDetailListByCode, {code : JSON.stringify(json)}, "json", function(data){
        if(data){
            var _data = data.object;
            var firstMsg = !noMessage && "==请选择==";
            $.each(_data, function (key) {
                if (value) {
                    jsonBindDrop("#" + key, firstMsg, _data[key], value);
                } else {
                    jsonBindDrop("#" + key, firstMsg, _data[key]);
                }
            });
            layform.render("select");
        }
    });
}
function initMoreDicVal (json, value) {
    This.jqueryAjax(Api.base.dataDictionary.getDataDictionaryDetailListByCode, {code : JSON.stringify(json)}, "json", function(data){
        if(data){
            var _data = data.object;
            $.each(_data, function (key) {
                if (value) {
                    jsonBindDropVal("#" + key, _data[key], value);
                }
            });
        }
    });
}
function jsonBindDropVal(eleid, data, object){
    var key = eleid.replace("#", "");
    var val = object && object[key];
    for (var i = 0; i < data.length; i++) {
        if (val == data[i].code) {
            $(eleid).val(data[i].name);
        }
    }
}
// 初始化时间
function initDateWdate(elemId, datetype) {
    elemId = elemId || "Wdate";
    // 时间处理
    $("." + elemId).each(function () {
        var thisValue = $(this).val();
        if (thisValue) {
            initDate($(this).attr("id"), thisValue, datetype);
        } else {
            initDate($(this).attr("id"), '', datetype);
        }
        $(this).attr("readonly", "readonly");
    });
}

// 初始化时间
function initDate(elemId, value, type) {
    type = type ? type : 'date';
    var format = type && type == 'datetime' ? "yyyy-MM-dd hh:mm:ss" : 'yyyy-MM-dd';
    if (value) {
        if (Number(value)) {
            value = dateFormat((Number(value)), format);
        } else {
            value = dateFormat(value, format);
        }
    }
    //日期
    laydate.render({
        elem: '#' + elemId,
        type: type,
        value: value ? new Date(value) : '',
        done: function(value, data, endDate) {
            try {
                var _this = this;
                siteDate(_this, value, data, endDate);
            } catch (e) {

            }
        }
    });
}

//初始化省级下拉
function initProvince (provinceCode, province, elemId, cityId) {
    elemId = elemId ? elemId : 'proProvince';
    cityId = cityId ? cityId : '';
    if (!province) {
        province = "530000";
    }
    //所在省
    $("#"+elemId).html("");
    $("#"+elemId).append("<option value=''>==请选择==</option>");
    This.jqueryAjax(Api.base.baseProvinceCity.provinceCityList, { parentId: "0", code: provinceCode }, "json", function(data){
        for (var key in data.object) {
            var provinceCity = data.object[key];
            if (provinceCity.code == province) {
                $("#"+elemId).append($("<option selected='selected'></option>").val(provinceCity.code).html(provinceCity.name));
            } else {
                $("#"+elemId).append($("<option></option>").val(provinceCity.code).html(provinceCity.name));
            }
        }
        layform.render("select");
        if (!province) {
            // 省 默认选择第一个
            //$("#proProvince option:eq(1)").attr("selected", true);
        }
        if ($("#"+elemId).val()) {
            bindCityId($("#"+elemId).val(), '',cityId);
        }
    })
}

//所在市下拉框
function bindCityId(province, city, elemId) {
    elemId = elemId ? elemId : 'proCity';
    $("#" + elemId).html("");
    $("#" + elemId).append("<option value=''>==请选择==</option>");
    This.jqueryAjax(Api.base.baseProvinceCity.provinceCityList, { parentId: province}, "json", function(data){
        for (var key in data.object) {
            var provinceCity = data.object[key];
            if (provinceCity.code == city) {
                $("#" + elemId).append($("<option selected='selected'></option>").val(provinceCity.code).html(provinceCity.name));
            } else {
                $("#" + elemId).append($("<option></option>").val(provinceCity.code).html(provinceCity.name));
            }
        }
        layform.render("select");
    });
}
//所在县区下拉框
function bindCountyId(city, county, elemId) {
    elemId = elemId ? elemId : 'proCounty';
    $("#" + elemId).html("");
    $("#" + elemId).append("<option value=''>==请选择==</option>");
    This.jqueryAjax(Api.base.baseProvinceCity.provinceCityList, { parentId: city}, "json", function(data){
        for (var key in data.object) {
            var provinceCity = data.object[key];
            if (provinceCity.code == county) {
                $("#" + elemId).append($("<option selected='selected'></option>").val(provinceCity.code).html(provinceCity.name));
            } else {
                $("#" + elemId).append($("<option></option>").val(provinceCity.code).html(provinceCity.name));
            }
        }
        layform.render("select");
    });
}

// 市县监听下拉框
function initSelect() {
    //初始化市级下拉列表
    layform.on('select(proProvince)', function (data) {
        bindCityId($("#proProvince").val());
        $("#proCounty").val("");
        layform.render("select");
    });

    //初始化县区下拉类表
    layform.on('select(proCity)', function (data) {
        bindCountyId($("#proCity").val());
    });
}

var back = function (event) {
    event.stopPropagation();
    window.history.go(-1);
};

var closeLayer = function (event) {
    top.layer.closeAll();
};

function toClose() {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
}

function _loading(handleClose) {
    loding = layer.load(3);
    if (handleClose !== 1) {
        setTimeout(function () {
            _loadingClose();
        }, 3000)
    }
}

function _loadingClose() {
    if (layer) {
        layer.close(loding);
        lodingCheck = null;
    }
}

function emptyInput() {
    $("*").find("input[id]").each(function (i) {
        $(this).val("");
    });
    $("*").find("textarea[id]").each(function (i) {
        $(this).val("");
    });
    layform.render();
}

function noSubmit (i) {
    var id = i || '#save' ;
    $(id).addClass('layui-disabled');
    $(id).attr('disabled', 'disabled');
    $(id).prop('disabled', true);
    $(id).text('数据提交中...');
}

function reSubmit (i) {
    var id = i || '#save';
    $(id).removeClass('layui-disabled');
    $(id).removeAttr('disabled');
    $(id).prop('disabled', false);
    $(id).text('提交');
}

function tableNumber (index, tableId) {
    var tableID = "table_list";
    if (tableId) {
        tableID = tableId;
    }
    var pageSize = $('#' + tableID).bootstrapTable('getOptions').pageSize;//通过表的#id 可以得到每页多少条
    var pageNumber = $('#' + tableID).bootstrapTable('getOptions').pageNumber;//通过表的#id 可以得到当前第几页
    if (pageSize && pageNumber) {
        return pageSize * (pageNumber - 1) + index + 1;    //返回每条的序号： 每页条数 * （当前页 - 1 ）+ 序号
    } else {
        return index + 1;
    }
}

function getParam(param, defaultValue) {
    if (URL_PARAM) {
        if (URL_PARAM[param] != "undefined" && URL_PARAM[param] != "null" && !!URL_PARAM[param]) {
            if (decodeURIComponent(URL_PARAM[param]) == 'true') {
                return true;
            } else if (decodeURIComponent(URL_PARAM[param]) == 'false') {
                return false;
            }
            return decodeURIComponent(decodeURIComponent(URL_PARAM[param]));
        }
        return defaultValue || "";
    }
}

function layformVerify (verify) {
    layform.verify(verify);
}

function getPrevIframe () {
    var windowName = getParam("windowName");
    if (windowName) {
        var doc = top.document.getElementById(windowName).contentWindow;
        return doc;
    }
}

function flushPrevIframe (tb) {
    var windowName = getParam("windowName");
    if (windowName) {
        var doc = top.document.getElementById(windowName).contentWindow;
        doc.windowloadList(tb);
        toClose();
    } else {
        closeFlushParent(parent);
    }
}

//高级搜索的显示和隐藏
var hFlag = 1;//标记是否隐藏
function showSlide() {
    if (hFlag) {
        $(".search").show();
        $("#searchToggle").html("普通搜索");
        hFlag = 0;
    } else {
        $(".search").hide();
        $("#searchToggle").html("高级搜索");
        hFlag = 1;
    }
}

function downFile(_this) {
    var filepath = $(_this).attr("filepath");
    var filename = $(_this).attr("filename");
    if (filename.indexOf(".doc") != -1 || filename.indexOf(".docx") != -1 ||
        filename.indexOf(".pdf") != -1 || filename.indexOf(".jpg") != -1 ||
        filename.indexOf(".png") != -1 || filename.indexOf(".jpeg") != -1 ||
        filename.indexOf(".xls") != -1 || filename.indexOf(".xlsx") != -1
    ) {
        location.href = filepath + "?attname=" + filename;
    } else {
        //filename = filename.substring(0, filename.lastIndexOf("."));
        location.href = Url.creatUrl(Api.common.download, {filePath: encodeURIComponent(filepath), fileName: encodeURIComponent(filename)})
    }
}

//判断字符长度
function strLen(_this, length, fix) {
    var obj = $(_this);
    var str = obj.val() || obj.html();
    var len = 0, subLen = 0;
    for (var i = 0; i < str.length; i++) {
        var c = str.charCodeAt(i);
        //单字节加1
        if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
            len++;
            if (len <= length) {
                subLen++;
            }
        } else {
            len += 2;
            if (len <= length) {
                subLen++;
            }
        }
    }
    if (len > length) {
        obj.val(str.substring(0, subLen - 1));
        obj.html(str.substring(0, subLen - 1));
        layerMessage("字符长度不能超过：" + length, 2, 2);
    }

    if (fix && Number(str) > 0) {
        obj.val(Number(str).toFixed(fix));
    }

}

/**
 * 获取标段元素 如果元素又值 就不可编辑
 */
function hasValAddClassDisabled () {
    $("input:not([onclick])").each(function(){
        if($(this).val()){
            $(this).addClass("layui-disabled");
            $(this).attr("disabled", "disabled");
        }
    });
    $("textarea").each(function(){
        if($(this).val()){
            $(this).addClass("layui-disabled");
            $(this).attr("disabled", "disabled");
        }
    });
    $("select").each(function(){
        if($(this).find("option:checked").length > 0 && $(this).find("option:checked").val()){
            $(this).addClass("layui-disabled");
            $(this).attr("disabled", "disabled");
        }
    });
    layform.render();
}
function getObjectById(id) {
    var form = {};
    $("#" + id + " input").each(function() {
        if ($(this).val()) form[$(this).attr("name")] = $(this).val().trim();
    });
    $("#" + id + " select").each(function() {
        if ($(this).val()) form[$(this).attr("name")] = $(this).val().trim();
    });
    $("#" + id + " textarea").each(function() {
        if ($(this).val()) form[$(this).attr("name")] = $(this).val().trim();
    });
    return form;
}

if (!Array.prototype.startsWith) {
    /**
     * 解决IE不支持startsWith
     * @param str
     * @returns {boolean}
     */
    String.prototype.startsWith=function(str){
        if(str==null||str==""||this.length==0||str.length>this.length)
            return false;
        if(this.substr(0,str.length)==str){
            return true;
        }else{
            return false;
        }
    };
}

if (!Array.prototype.endsWith) {
    /**
     * 解决IE不支持endsWith
     * @param str
     * @returns {boolean}
     */
    String.prototype.endsWith=function(str){
        if(str==null||str==""||this.length==0||str.length>this.length)
            return false;
        if(this.substr(this.length - str.length)==str){
            return true;
        }else{
            return false;
        }
    };
}

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(elt, from) {
        var len = this.length >>> 0;
        var from = Number(arguments[1]) || 0;
        from = (from < 0) ? Math.ceil(from) : Math.floor(from);
        if (from < 0)
            from += len;
        for (; from < len; from++) {
            if (from in this && this[from] === elt)
                return from;
        }
        return -1;
    };
}

/**
 * ie好像通过.name获取不到方法名，需要的通过该方法获取
 * @param tmp
 * @returns {string}
 */
function getFunctionName(tmp){
    return /function\s*(\w*)/i.exec(tmp)[1];
}

/**
 * 判断js对象是否是dom对象
 * @param obj
 * @returns {boolean}
 */
function isElement(obj){
    return (typeof HTMLElement === 'object')
        ?(obj instanceof HTMLElement)
        :!!(obj && typeof obj === 'object' && (obj.nodeType === 1 || obj.nodeType === 9) && typeof obj.nodeName === 'string');
}

var pressEnter = function(element, enterFuc) {
    try {
        $(element).unbind("keypress");
        $(element).bind("keypress", function(e) {
            if(e.which == 13){
                eval(enterFuc);
                return false;
            }
        });
    }catch(e){
        return false;
    }
};

function ViewAndUpdate(value,row, index){
    return "<a href=\"javascript:void(0);\" class=\"btn btn-default btn-sm common-add\" onclick=\"commonViewTab('',Api.sce.sginup.getSginUpListById, {id:idcard})\">\n" +
        "                               查看" +
        "                            </a>  <a href=\"javascript:void(0);\" class=\"btn btn-default btn-sm common-add\" onclick=\"commonUpdate(Api.sce.sginup.addHtml,{id:idcard}, '修改考生信息')\">\n" +
        "                                <span class=\"icon  icon-plus-sign handle_ioc \"></span>修改" +
        "                            </a>"
}

//通用
function table_common_int(table, row, table_name, type, opts) {
	if (type == 1) {
	    return "<a href='javascript:;' class='table_row_handle' onclick=\"common_update_int('" + table + "', '" +　table_name + "', '0', '" + row.id + "', '"+ opts +"')\" ><img src='/admin/images/icon/accept.png'></a>";
	} if (type == 0) {
	    return "<a href='javascript:;' class='table_row_handle' onclick=\"common_update_int('" + table + "', '" +　table_name + "', '1', '" + row.id + "', '"+ opts +"')\" ><img src='/admin/images/icon/unaccept.png'></a>";
	}
}

function getCurrentYear(){
	var date = new Date();
	return date.getFullYear() + '年';
}


function changeTwoDecimal_f(x)
{
    var f_x = parseFloat(x);
    if (isNaN(f_x))
    {
        return 0;
    }
    var f_x = Math.round(x*100)/100;
    var s_x = f_x.toString();
    var pos_decimal = s_x.indexOf('.');
    if (pos_decimal < 0)
    {
        pos_decimal = s_x.length;
        s_x += '.';
    }
    while (s_x.length <= pos_decimal + 2)
    {
        s_x += '0';
    }
    return s_x;
}